-module(p14).
-compile(export_all).

main(N, M) ->
    Seq = lists:seq(N, M),
    Lens = lists:map(fun collatz_length/1, Seq),
    Tuples = lists:zip(Lens, Seq),
    Max = lists:max(Lens),
    {value, {Max, Res}} = lists:keysearch(Max, 1, Tuples),
    Res.


collatz_length(Number) ->
    lists:flatlength(collatz_sequence(Number)).

collatz_sequence([Head | _Tail]=Z) when Head =:= 1 -> Z;
collatz_sequence([Head | _Tail]=Z) ->
    case Head rem 2 of
        0 -> collatz_sequence([Head div 2 | Z]);
        1 -> collatz_sequence([Head * 3 + 1 | Z])
    end;
collatz_sequence(Number) -> collatz_sequence([Number]).
